package com.example.qihuibao.widget.view

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.qihuibao.R
import com.example.qihuibao.bean.*
import com.example.qihuibao.constant.Config
import com.example.qihuibao.constant.Global
import com.example.qihuibao.dao.MyDatabase
import com.example.qihuibao.module.main.MainActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.lang.StringBuilder

/**
 *     author : cwwei
 *     e-mail : 494545699@qq.com
 *     date   : 2022/08/13
 *     desc   :
 */
class HomeLayout(ctx:Context) : FrameLayout(ctx) {
    private lateinit var root:View
    private lateinit var llInit:FrameLayout
    private lateinit var pbInit:ProgressBar
    private lateinit var tvInit:TextView
//    private lateinit var llDevInfo:LinearLayout
    private lateinit var tvExitInit:TextView
//    private lateinit var tvCanteen:TextView
//    private lateinit var tvMeal:TextView
    private lateinit var tvTotalOrder:TextView
    private lateinit var tvTotalUse:TextView
    private lateinit var tvTotalNoUse:TextView
    private lateinit var rvUseRecord:CommonRecyclerView


    private lateinit var tv_enterprise_info:TextView
    private lateinit var tv_canteen_info:TextView
    private lateinit var tv_meal_info:TextView
    private lateinit var rv_mealset:CommonRecyclerView
    private lateinit var tv_employ_info:TextView
    private lateinit var tv_employ_order:TextView


    init {
        root = LayoutInflater.from(ctx).inflate(R.layout.layout_home, this, true)
        initView()
    }

    private fun initView() {
        llInit = root.findViewById(R.id.ll_init)
        pbInit = root.findViewById(R.id.pb_init)
        tvInit = root.findViewById(R.id.tv_init)
//        llDevInfo = root.findViewById(R.id.ll_dev_info)
        tvExitInit = root.findViewById(R.id.tv_exit_init)
//        tvCanteen = root.findViewById(R.id.tv_canteen)
//        tvMeal = root.findViewById(R.id.tv_meal)
        tvTotalOrder = root.findViewById(R.id.tv_total_order)
        tvTotalUse = root.findViewById(R.id.tv_total_use)
        tvTotalNoUse = root.findViewById(R.id.tv_total_no_use)
        rvUseRecord = root.findViewById(R.id.rv_use_record)

        tv_enterprise_info = root.findViewById(R.id.tv_enterprise_info)
        tv_canteen_info = root.findViewById(R.id.tv_canteen_info)
        tv_meal_info = root.findViewById(R.id.tv_meal_info)
        rv_mealset = root.findViewById(R.id.rv_mealset)
        tv_employ_info = root.findViewById(R.id.tv_employ_info)
        tv_employ_order = root.findViewById(R.id.tv_employ_order)

        tvExitInit.setOnClickListener {
            if (context is MainActivity) {
                (context as MainActivity).exitInitDevice()
            }
        }
        root.findViewById<View>(R.id.btn_test_scan_initcode).setOnClickListener {
            (context as MainActivity).initDevice("J/TkqElHt9dc8a6mj7cF2q4kJS9pr0ZrLKcsgMtrLIi9Cy3chTQiP7RtfL0/mxsJ/cfgorI20FgAYGoAtitBB2BCspQsW9yCORw6t7nvO16CFeEXKNL9Igg9TIZiBoavvNUuFrz8KA4=")
        }
        root.findViewById<View>(R.id.btn_test_scan).setOnClickListener {
            (context as MainActivity).authUser(UserIdentify(null, UserIdentify.CodeBean("000001"), null))
        }
        root.findViewById<View>(R.id.btn_test_writeoff).setOnClickListener {
            (context as MainActivity).writeOff()
        }
        root.findViewById<View>(R.id.btn_test_scene).setOnClickListener {
            (context as MainActivity).sceneMeal()
        }
    }

    private fun showMealSet() {
        val feeList = Global.currentMealInfoBean?.FeeList
        val list = Global.currentMealInfoBean?.MealSetlList
        if (list.isNullOrEmpty()) return
        rv_mealset.init(
            R.layout.item_mealset,
            LinearLayoutManager(context, RecyclerView.VERTICAL, false),
            list,
            {parent, pos ->
                parent.findViewById<TextView>(R.id.tv_mealset_name).text = context.getString(R.string.mealset_name, list[pos].MealSetName)
                parent.findViewById<TextView>(R.id.tv_mealset_status).text = context.getString(R.string.mealset_status, if (list[pos].Status=="0") "不开通" else "开通")
//                parent.findViewById<TextView>(R.id.tv_mealset_PerOrderLimit).text = context.getString(R.string.mealset_PerOrderLimit, list[pos].PerOrderLimit)
//                parent.findViewById<TextView>(R.id.tv_mealset_PerSpotLimit).text = context.getString(R.string.mealset_PerSpotLimit, list[pos].PerSpotLimit)
//                parent.findViewById<TextView>(R.id.tv_mealset_PerTotalLimit).text = context.getString(R.string.mealset_PerTotalLimit, list[pos].PerTotalLimit)
//                parent.findViewById<TextView>(R.id.tv_mealset_AllOrderLimit).text = context.getString(R.string.mealset_AllOrderLimit, list[pos].AllOrderLimit)
//                parent.findViewById<TextView>(R.id.tv_mealset_AllSpotLimit).text = context.getString(R.string.mealset_AllSpotLimit, list[pos].AllSpotLimit)
//                parent.findViewById<TextView>(R.id.tv_mealset_AllTotalLimit).text = context.getString(R.string.mealset_AllTotalLimit, list[pos].AllTotalLimit)
                //查找套餐的收费标准
                (context as MainActivity).lifecycleScope.launch {
                    var mealSetFee :MealSetFee? = null
                    val mealSetId = list[pos].MealSetID
                    withContext(Dispatchers.IO) {
                        val feeBean = MyDatabase.db.feesInfoDao().queryInId(Config.currentCanteenId, Config.currentMealId)
                        if (feeBean != null && !feeBean.MealSetFeeList.isNullOrEmpty()) {
                            for (item in feeBean.MealSetFeeList) {
                                if (item.MealSetID == mealSetId) {
                                    mealSetFee = item
                                    break
                                }
                            }
                        }
                    }
                    if (mealSetFee != null) {
                        parent.findViewById<TextView>(R.id.tv_mealSet_fee).text = context.getString(R.string.mealset_fee,
                            "\n订餐第一份价格（分，下同）：${mealSetFee?.OrderFee}\n" +
                            "订餐第二份价格：${mealSetFee?.OrderFee2}\n" +
                            "订餐第三份后价格：${mealSetFee?.OrderFee3}\n" +
                            "现场第一份价格（分，下同）：${mealSetFee?.SpotFee}\n" +
                            "现场第二份价格：${mealSetFee?.SpotFee2}\n" +
                            "现场第三份后价格：${mealSetFee?.SpotFee3}\n"
                        )
                    }else {
                        parent.findViewById<TextView>(R.id.tv_mealSet_fee).text = context.getString(R.string.mealset_fee, "无")
                    }
                }
            }
        )
    }

    private fun showUseRecord() {
        (context as MainActivity).lifecycleScope.launch {
            val useList = mutableListOf<RspUseDetailBean.Use>()
            withContext(Dispatchers.IO) {
                val list = MyDatabase.db.useInfoDao().queryAll()
                if (!list.isNullOrEmpty()) {
                    useList.addAll(list)
                    useList.addAll(list)//test
                }
            }
            useList.add(0, RspUseDetailBean.Use(EmpName = "姓名", TranTime = "取餐时间", MealID = "餐别", MealSetID = "套餐", Status = "成功"))
            rvUseRecord.init(
                R.layout.item_use_record,
                LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                useList,
                {parent, pos ->
                    parent.findViewById<TextView>(R.id.tv_EmpName).text = useList[pos].EmpName
                    parent.findViewById<TextView>(R.id.tv_TranTime).text = useList[pos].TranTime
                    parent.findViewById<TextView>(R.id.tv_MealID).text = useList[pos].MealID
                    parent.findViewById<TextView>(R.id.tv_MealSetID).text = useList[pos].MealSetID
                    parent.findViewById<TextView>(R.id.tv_Count).text = if (pos == 0) "取餐数" else "${useList[pos].Count}"
                    parent.findViewById<TextView>(R.id.tv_OrderCount).text = if (pos == 0) "总订数" else "${useList[pos].OrderCount}"
                    parent.findViewById<TextView>(R.id.tv_Status).text = if (pos == 0) "成功" else (if (useList[pos].Status=="1") "yes" else "no")
                }
            )
        }
    }

    private fun setCanteenData() {
        tv_enterprise_info.text = "企业名称：${Global.rspQueryEnterpriseInfoBean?.CorpName}\n" +
                "状态：${if (Global.rspQueryEnterpriseInfoBean?.Status=="0") "正常" else "冻结"}"

        tv_canteen_info.text = "餐厅名称：${Global.currentCanteenInfoBean?.CantName}\n" +
                "状态：${if (Global.currentCanteenInfoBean?.Status=="0") "正常" else "冻结"}\n" +
                "订餐模式：${getOrderMode()}\n" +
//                "业务模式：${getServiceType()}\n" +
                "取餐方式：${getUseMode()}\n" +
                "业务流程：${getFlowType()}"
//                "查询余额开关：${if (Global.currentCanteenInfoBean?.QryBalanceFlag=="0") "关" else "开"}\n" +
//                "查询消费明细开关：${if (Global.currentCanteenInfoBean?.QryConsumeFlag=="0") "关" else "开"}\n" +
//                "第二(补贴)账户开关：${if (Global.currentCanteenInfoBean?.SecondAccFlag=="0") "关" else "开"}\n" +
//                "开通渠道：${getOpenChannel()}"

        tv_meal_info.text = "餐别名称：${Global.currentMealInfoBean?.MealName}\n" +
                "状态：${if (Global.currentMealInfoBean?.Status=="0") "不开餐" else "开餐"}\n" +
//                "订餐开关：${if (Global.currentMealInfoBean?.OrderFlag=="0") "关" else "开"}\n" +
                "现场用餐：${if (Global.currentMealInfoBean?.SpotFlag=="0") "关" else "开"}\n" +
//                "退餐开关：${if (Global.currentMealInfoBean?.CancelFlag=="0") "关" else "开"}\n" +
//                "订餐周历：${if (Global.currentMealInfoBean?.WeekCalendar=="0") "关" else "开"}\n" +
                "用餐开始时间：${Global.currentMealInfoBean?.UseBeginTime}\n" +
                "用餐结束时间：${Global.currentMealInfoBean?.UseEndTime}\n" +
//                "现场用餐开始时间：${Global.currentMealInfoBean?.SpotUseBeginTime}\n" +
//                "现场用餐结束时间：${Global.currentMealInfoBean?.SpotUseEndTime}\n" +
//                "订餐截止时间：提前${Global.currentMealInfoBean?.OrderDeadlineDate}天，${Global.currentMealInfoBean?.OrderDeadlineTime}\n" +
//                "退餐截止时间：提前${Global.currentMealInfoBean?.CancelDeadlineDate}天，${Global.currentMealInfoBean?.CancelDeadlineTime}\n" +
//                "个人订餐限额：${Global.currentMealInfoBean?.PerOrderLimit}\n" +
//                "个人现场限额：${Global.currentMealInfoBean?.PerSpotLimit}\n" +
//                "个人总量限额：${Global.currentMealInfoBean?.PerTotalLimit}\n" +
//                "总订餐限额：${Global.currentMealInfoBean?.AllOrderLimit}\n" +
//                "总现场限额：${Global.currentMealInfoBean?.AllSpotLimit}\n" +
//                "总的总量限额：${Global.currentMealInfoBean?.AllTotalLimit}\n" +
                "订餐模式：${getOrderMode()}\n" +
                "支持配送：${if (Global.currentMealInfoBean?.DeliverFlag=="0") "否" else "是"}"

        showMealSet()

        tvTotalOrder.text = context.getString(R.string.total_order, Global.totalOrder)
        tvTotalUse.text = context.getString(R.string.total_use, Global.totalUse)
        tvTotalNoUse.text = context.getString(R.string.total_no_use, Global.totalOrder-Global.totalUse)

        showUseRecord()
    }

    private fun getServiceType(): String {
        if (Global.currentCanteenInfoBean?.ServiceType.isNullOrBlank()) {
            return ""
        }else {
            val charArray = Global.currentCanteenInfoBean?.ServiceType?.toCharArray()
            val sb = StringBuilder()
            for (i in 0 until charArray!!.size) {
                when(i) {
                    0 -> sb.append("订餐-${if (charArray[i] == '0') "不开通" else "开通"},")
                    1 -> sb.append("充值-${if (charArray[i] == '0') "不开通" else "开通"},")
                    2 -> sb.append("订餐统计-${if (charArray[i] == '0') "不开通" else "开通"},")
                    3 -> sb.append("扫码支付取餐-${if (charArray[i] == '0') "不开通" else "开通"},")
                    4 -> sb.append("团餐（批量订餐/退餐）-${if (charArray[i] == '0') "不开通" else "开通"},")
                    5 -> ""
                    6 -> sb.append("停餐-${if (charArray[i] == '0') "不开通" else "开通"}")
                }
            }
            return sb.toString()
        }
    }

    private fun getUseMode(): String {
        if (Global.currentCanteenInfoBean?.UseMode.isNullOrBlank()) {
            return ""
        }else {
            val charArray = Global.currentCanteenInfoBean?.UseMode?.toCharArray()
            val sb = StringBuilder()
            for (i in 0 until charArray!!.size) {
                when(i) {
                    0 -> sb.append(if (charArray[i] == '1') "出示取餐信息 - " else "")
                    1 -> sb.append(if (charArray[i] == '1') "扫码取餐 - " else "")
                    2 -> sb.append(if (charArray[i] == '1') "系统对接" else "")
                }
            }
            return sb.toString()
        }
    }

    private fun getFlowType(): String {
        if (Global.currentCanteenInfoBean?.FlowType.isNullOrBlank()) {
            return ""
        }else {
            return when(Global.currentCanteenInfoBean?.FlowType) {
                "0" -> "自动"
                "1" -> "客户确认"
                "2" -> "客服确认"
                "3" -> "客服-客户确认"
                "4" -> "客户-客服确认"
                else -> ""
            }
        }
    }

    private fun getOpenChannel(): String {
        if (Global.currentCanteenInfoBean?.OpenChannel.isNullOrBlank()) {
            return ""
        }else {
            val charArray = Global.currentCanteenInfoBean?.OpenChannel?.toCharArray()
            val sb = StringBuilder()
            for (i in 0 until charArray!!.size) {
                when(i) {
                    0 -> sb.append("融e行-${if (charArray[i] == '0') "不开通" else "开通"},")
                    1 -> sb.append("融e联-${if (charArray[i] == '0') "不开通" else "开通"},")
                    5 -> sb.append("H5页面-${if (charArray[i] == '0') "不开通" else "开通"}")
                }
            }
            return sb.toString()
        }
    }

    private fun getOrderMode(): String {
        if (Global.currentCanteenInfoBean?.OrderMode.isNullOrBlank()) {
            return ""
        }else {
            return when(Global.currentCanteenInfoBean?.OrderMode) {
                "1" -> "套餐"
                "2" -> "点餐"
                "3" -> "简约"
                "4" -> "混合"
                else -> ""
            }
        }
    }



    fun showDevInit() {
        llInit.visibility = View.VISIBLE
        tvInit.text = "请扫码初始化"
        tvExitInit.visibility = if (Config.deviceInit) View.VISIBLE else View.GONE
    }

    fun showCanteen() {
        llInit.visibility = View.GONE
//        llDevInfo.visibility = View.VISIBLE
        setCanteenData()
    }

    fun showEmployInfo(bean: RspQueryEmployInfoBean.Employ?) {
        if (bean == null) {
            tv_employ_info.text = "找不到员工信息！"
        }else {
            tv_employ_info.text =
                "员工姓名：${bean.EmpName}\n" +
                        "余额：${bean.Balance}\n" +
                        "状态：${if (bean.Status == "1") "正常" else (if (bean.Status == "2") "挂失" else "冻结")}"
        }
    }

    fun showEmployOrder(bean: RspQueryOrderInfoBean.Order?) {
        if (bean == null) {
            tv_employ_order.text = "找不到订餐信息！"
        }else {
            tv_employ_order.text =
                "订餐时间：${bean.MealDate}-${bean.TranTime}\n" +
                        "订餐流水号：${bean.TranID}\n" +
                        "订餐份数：${bean.Count}\n" +
                        "已取餐份数：${bean.UseCount}\n" +
                        "餐别：${bean.MealID}\n" +
                        "套餐：${bean.MealSetID}\n" +
                        "类型：${bean.OrderType}\n"
        }
    }
}